package com.cxq.safe.synchronizedblocked;

/**
 * Created by cxq on 2020/7/25.
 */
public class Tickets  implements Runnable{

    //创建一个锁对象
    Object obj = new Object();

    private int ticket = 100;

    @Override
    public void run() {
        while(true) {
            synchronized (obj) {
                if (ticket > 0) {
                    try {
                        //模拟出票时间
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //打印进程号和票号，票数减1
                    String name = Thread.currentThread().getName();
                    System.out.println("线程" + name + "售票" + ticket--);
                }
            }
        }
    }
}
